package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.Date;

import database.Database;

public class AppointmentList {
	ArrayList<Appointment> appointments;
	int userId;
	Date start;
	Date end;
	
	/*
	 * REGION public constructor
	 */
	public AppointmentList(int userId) {
		setUserId(userId);
		setStart(new Date(111, 03, 10));
		setEnd(new Date(111, 03, 17));
		System.out.println("klarte alt fram til load i appointmentlist");
		load();
	}
	public AppointmentList(int userId, Date start) {
		setUserId(userId);
		if(start.getDay()!=0){
			start = new Date(start.getYear(), start.getMonth(), start.getDate()-start.getDay());
		}
		setStart(start);
		Date slutt = new Date(start.getYear(), start.getMonth(), start.getDate()+7);	
		
		setEnd(slutt);
		load();
	}
	
	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public Date getStart() {
		return start;
	}

	public void setStart(Date start) {
		this.start = start;
	}

	public Date getEnd() {
		return end;
	}

	public void setEnd(Date end) {
		this.end = end;
	}

	/*
	 * REGION public getters
	 */
	public ArrayList<Appointment> getPersonlist() {
		return appointments;
	}
	
	public int getPersonCount() {
		return appointments.size();
	}
	
	/*
	 * REGION public methods
	 */
	public void load() {
		
		// Establish a connection to the database
		Database database = new Database();
		database.connectToDatabase();
		System.out.println("connectet til db");
		try {
			
			ResultSet rs = database.getAppointmentsFromWeek(userId, start.toString(), end.toString());
			
			appointments = new ArrayList<Appointment>();
			System.out.println("initialisert");
			while (rs.next()) {
				int appointmentId = rs.getInt("ID");
				Appointment appointment = new Appointment(appointmentId);
				appointments.add(appointment);
			}
		}
		catch(SQLException e) {
			System.out.println("fikk sqlexception  fra getappointmentsfromweek");
			e.printStackTrace();
		}	
		database.disconnectDatabase();
	}
	public Object[][] objectForJTable(){
		Object[][] uke = new Object[4][7];
		int tid = 0;
		for (int i = 0; i<appointments.size(); i++){
			if(appointments.get(i).getFromPointOfTime().getHours()>=8){
			uke[(appointments.get(i).getFromPointOfTime().getHours()-7)/2][appointments.get(i).getDate().getDay()] = appointments.get(i).getTitle();
			}else{
				System.out.println(appointments.get(i).getFromPointOfTime().getHours());
			}
		}
		return uke;
	}
}
